package com.itnan.user.controller;

import com.itnan.user.domain.User;
import com.itnan.user.service.UserService;
import com.itnan.user.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by tangjian on 27/4/14.
 */
@Controller
@RequestMapping(value = "/")
public class HomeController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "")
    public String home() {
        return "login";
    }

    @RequestMapping(value = "/login")
    public String login(Model model, HttpServletRequest request) {
        String userName = request.getParameter("username");
        String userPassword = request.getParameter("userpassword");
        if (StringUtil.isEmpty(userName) || StringUtil.isEmpty(userPassword)) {
            model.addAttribute("error", "用户名或密码不能空");
            return "login";
        }
        User user = userService.findByUserNameAndUserPassword(userName, userPassword);
        if (user == null) {
            model.addAttribute("error", "用户名不存在");
            return "login";
        }
        if (user.getType() == 0) {
            request.getSession().setAttribute("user", user);
            // 管理员
            return "redirect:/admin/main";
        }
        if (user.getType() == 1) {
            // 推广者
            request.getSession().setAttribute("user", user);
            return "redirect:/user/main";
        }
        return "login";
    }

    @RequestMapping(value = "/register")
    public String register() {
        return "register";
    }

}
